package cn.edu.nchu.fragmentdemo.utils;

import android.app.Activity;
import android.app.Dialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.SharedPreferences;
import android.os.Environment;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;

import androidx.appcompat.app.AlertDialog;


import cn.edu.nchu.fragmentdemo.R;
import cn.edu.nchu.fragmentdemo.MainActivity;
import org.osmdroid.api.IMapController;
import org.osmdroid.tileprovider.modules.ArchiveFileFactory;
import org.osmdroid.tileprovider.modules.IArchiveFile;
import org.osmdroid.tileprovider.modules.OfflineTileProvider;
import org.osmdroid.tileprovider.tilesource.FileBasedTileSource;
import org.osmdroid.tileprovider.tilesource.TileSourceFactory;
import org.osmdroid.tileprovider.util.SimpleRegisterReceiver;
import org.osmdroid.util.GeoPoint;
import org.osmdroid.views.MapView;
import org.osmdroid.views.overlay.MinimapOverlay;
import org.osmdroid.views.overlay.Overlay;
import org.osmdroid.views.overlay.ScaleBarOverlay;
import org.osmdroid.views.overlay.compass.CompassOverlay;
import org.osmdroid.views.overlay.compass.InternalCompassOrientationProvider;
import org.osmdroid.views.overlay.gestures.RotationGestureOverlay;
import org.osmdroid.views.overlay.gridlines.LatLonGridlineOverlay2;
import org.osmdroid.views.overlay.mylocation.GpsMyLocationProvider;
import org.osmdroid.views.overlay.mylocation.MyLocationNewOverlay;

import java.io.File;
import java.util.List;
import java.util.Set;

import static org.osmdroid.tileprovider.tilesource.TileSourceFactory.MAPNIK;

/**
 * @author Wendy
 */
public class MapBasicOperationUtil {
    private String TAG = "MapBasicOperationUtil";
    public static int flag = 0;
    //swx new JTAC信息点击回到JTAC位置 jtac创建falg
    public static int jtacCreatedFlag = 0;
    MainActivity mainActivity;
    static volatile MapBasicOperationUtil mapBasicOperationUtil = null;
    SharedPreferences app_config;
    Context context;
    //地图组件
    MapView mMapView = null;
    //地图控制器
    IMapController mapController;
    //地图当前zoom等级
    double nowZoom = 12;
    //地图当前中心位置
    //swx repair 设置地图中心
    //GeoPoint nowLocation = new GeoPoint(16.7529084594605, 43.2118125329342);//老地图 红海
    //GeoPoint nowLocation = new GeoPoint(42.140270896, 86.832571001);//新地图（与实验室相同） 新疆
    GeoPoint nowLocation = new GeoPoint(28.68, 115.89);//南昌

    //GeoPoint nowLocation=new GeoPoint(28.68,115.85);
    //旋转图层
    RotationGestureOverlay mRotationGestu;
    //指南针图层
    CompassOverlay mCompassOverlay;
    //网格图层
    LatLonGridlineOverlay2 latLonGridlineOverlay2;
    //比例尺
    ScaleBarOverlay scaleBarOverlay;
    //
    TextView jtac_info;
    Button btn_jtac;
    double maxZoom = 22;
    double minZoom = 6;
    private List<Overlay> initOverlay;

    /**
     * Constructure
     *
     * @param mMapView
     * @param context
     */
    public MapBasicOperationUtil(MapView mMapView, Context context) {
        this.mMapView = mMapView;
        this.context = context;
        mapController = mMapView.getController();
        mainActivity = (MainActivity) MainActivity.getActivity();
        app_config = context.getSharedPreferences("app_config", Activity.MODE_PRIVATE);
    }

    /**
     * getInstance单例
     *
     * @param mapView
     * @param context
     * @return
     */
    public static MapBasicOperationUtil getInstance(MapView mapView, Context context) {
        if (mapBasicOperationUtil == null) {
            mapBasicOperationUtil = new MapBasicOperationUtil(mapView, context);
        }
        return mapBasicOperationUtil;
    }

    /**
     * 初始化地图
     * 最大放大尺寸
     * 最小缩小尺寸
     * 初始化zoom尺寸
     * 初始化地图资源
     * 初始化地图中心
     * 自由旋转
     * 双指放缩
     * 指南针图层
     * 显示网格图层
     * 显示自己location
     */
    public void initMap() {
        //最大最小放缩尺寸
//        mainActivity.appendLog("地图初始化",Log.INFO);
        maxZoom = Integer.parseInt(app_config.getString("maxZoom", "22"));
        minZoom = Integer.parseInt(app_config.getString("minZoom", "4"));
        nowZoom = (maxZoom - minZoom) / 2 + minZoom;
        mMapView.setMaxZoomLevel(maxZoom);
        mMapView.setMinZoomLevel(minZoom);
        //swx rapair 地图加载 设置读取地图文件  20210510  xxp
        //loadResourse("test2.mbtiles");
        //loadResourse("99.mbtiles");
        //loadResourse("2121.gmp");
        //loadResourse("2021_test2.sqlite");
        //loadResourse("2021_test.sqlite");
        //初始zoom尺寸
        setMapZoom(nowZoom);
        //swx repair 地图加载 设置初始地图大小级数
        //地图中心
        //nowLocation = new GeoPoint(mMapView.getMapCenter().getLatitude(),mMapView.getMapCenter().getLongitude());
        setMapCenter(nowLocation);
        //多点触控
        openMultiTouch();
        //关闭自由旋转
        closeRotationGestur();

        //swx repair 关闭指南针控件
        //显示指南针
        //showCompass();

        //载入marker图层
//        initOverlay = DbManagerUtil.getInstance().loadAllMarkerFromDb();
//        mMapView.getOverlays().addAll(initOverlay);

        //设置JTAC
//        setJTAC_Info("s");
//        setJTAC_Info();
    }

    /**
     * 设置JTAC_INFO
     */
//    public void setJTAC_Info() {
//        jtac_info.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View view) {
//                //swx new 添加goto_jtac功能
//                if (flag == 0) {
//                    MyOverlayManager.getInstance().addMyOverlay("JTAC", flag);
//                    flag = 1;
//                }
//                if (jtacCreatedFlag == 1) {
//                    MyMarkerEntity jtacEntity = (MyMarkerEntity) AppDataManager.getInstance().getInfoJTAC().get("JTAC");
//                    GeoPoint myGeoPoint = new GeoPoint(jtacEntity.getLatitude(), jtacEntity.getLongitude());
//                    mMapView.setExpectedCenter(myGeoPoint);
//                }
//
//            }
//        });
//    }

    public void setJTAC_Info(String s) {
        jtac_info.setText("点击这里\n放置JTAC位置");
    }

//    public void setJTAC_Info(Double longitude, Double latitude) {
//        System.out.println("setInfo");
//        jtac_info.setText("JTAC信息:" +
//                "\n经度：" + DFM.printLongLongDFM(longitude) +
//                "\n纬度：" + DFM.printLatLongDFM(latitude));
//    }

    //sing a song - 如烟 - 七岁的那一年 抓住那只蝉 以为能抓住夏天 十七岁的那年 吻过他的脸 就以为和他能永远

    /**
     * 文件夹下地图文件
     * 加后缀，如：myMBTiles.mbtiles
     *
     * @param fileName
     */

    public void loadResourse(String fileName) {
       /*String strFilepath = Environment.getExternalStorageDirectory().getPath() + File.separator +
                "osmdroid"+ File.separator+fileName; // 在 此处替换自己的资源*/
        //String strFilepath =  context.getExternalFilesDir("osmdroid").getPath()+ File.separator+fileName;
        String strFilepath;
        File dir = new File(Environment.getExternalStorageDirectory() + "/AdvanceTactics/");
        if (dir.exists() && dir.canWrite()) {
            strFilepath = dir.getAbsolutePath() + File.separator + fileName;
        } else {
            dir.mkdir();
            strFilepath = dir.getAbsolutePath() + File.separator + fileName;
        }
        Log.d(TAG, strFilepath);
        File exitFile = new File(strFilepath);
        //String fileName = "myMBTiles.mbtiles";
        if (!exitFile.exists() && !fileName.contains(".")) {
            mMapView.setTileSource(MAPNIK);
        } else {
            fileName = fileName.substring(fileName.lastIndexOf(".") + 1);
            if (fileName.length() == 0)
                return;
            //对不同类型的地图进行加载
//             extensionMap.put("zip", ZipFileArchive.class);
//             if(VERSION.SDK_INT >= 10) {
//             extensionMap.put("sqlite", DatabaseFileArchive.class);
//             extensionMap.put("mbtiles", MBTilesFileArchive.class);
//             extensionMap.put("gemf", GEMFFileArchive.class);
            if (ArchiveFileFactory.isFileExtensionRegistered(fileName)) {
                try {
                    OfflineTileProvider tileProvider = new OfflineTileProvider(new
                            SimpleRegisterReceiver(context),
                            new File[]{exitFile});
                    mMapView.setTileProvider(tileProvider);
                    String source = "";
                    IArchiveFile[] archives = tileProvider.getArchives();
                    if (archives.length > 0) {
                        Set<String> tileSources = archives[0].getTileSources();
                        if (!tileSources.isEmpty()) {
                            source = tileSources.iterator().next();
                            mMapView.setTileSource(FileBasedTileSource.getSource(source));
                        } else {
                            mMapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
                        }
                    } else {
                        mMapView.setTileSource(TileSourceFactory.DEFAULT_TILE_SOURCE);
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    }

    /**
     * 地图中心坐标
     */
    public void setMapCenter(GeoPoint centerPoint) {
        mapController.setCenter(centerPoint);
    }

    /**
     * 地图缩放等级
     */
    public void setMapZoom(double n) {
        mapController.setZoom(n);
        this.nowZoom = n;
    }

    /**
     * 打开地图双指放缩
     * 当前无法获取双指缩放后的地图zoom等级，点击放大缩小会变化
     */
    public void openMultiTouch() {
        mMapView.setMultiTouchControls(true);
        nowZoom = mMapView.getZoomLevelDouble();
        if (nowZoom >= maxZoom) {
            //swx new 20210429 洛客UI优化 界面整合Toast.makeText(context, "已放大到最大", Toast.LENGTH_LONG).show();
        } else if (nowZoom <= minZoom) {
            //swx new 20210429 洛客UI优化 界面整合Toast.makeText(context, "已缩小到最小", Toast.LENGTH_LONG).show();
        }
    }

    /**
     * 关闭地图双指放缩
     * 当前无法获取双指缩放后的地图zoom等级，点击放大缩小会变化
     */
    public void closeMultiTouch() {
        mMapView.setMultiTouchControls(false);
    }

    /**
     * 按键地图放大
     * 单击按键
     */
    public void enlargeMapZoom() {
        if (nowZoom < maxZoom) {
            setMapZoom(nowZoom + 0.5);
            nowZoom += 0.5;
        } else {
            //swx new 20210429 洛客UI优化 界面整合Toast.makeText(context, "已放大到最大", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 按键地图缩小
     */
    public void reduceMapZoom() {
        if (nowZoom > minZoom) {
            mapController.setZoom(nowZoom - 0.5);
            nowZoom -= 0.5;
        } else {
            //swx new 20210429 洛客UI优化 界面整合Toast.makeText(context, "已缩小到最小", Toast.LENGTH_SHORT).show();
        }
    }

    /**
     * 锁定地图
     */
    public void closeScale() {
        //禁止放大缩小
        mMapView.setMaxZoomLevel(nowZoom);
        mMapView.setMinZoomLevel(nowZoom);
        //禁止双指操作
        closeMultiTouch();
        //禁止拖动

        //禁止旋转
        closeRotationGestur();
    }

    /**
     * 解除锁定
     */
    public void openScale() {
        mMapView.setMinZoomLevel(minZoom);
        mMapView.setMaxZoomLevel(maxZoom);
        openMultiTouch();
    }

    /**
     * 添加指南针图层
     */
    public void showCompass() {
        mCompassOverlay = new CompassOverlay(context, new InternalCompassOrientationProvider(context), mMapView);
        mCompassOverlay.enableCompass();
        mMapView.getOverlays().add(mCompassOverlay);
        // MyOverlayManagerUtil.getInstance(context,mMapView).addOverlay(MyOverlayManagerUtil.getUid(),mCompassOverlay);
        mMapView.onResume();
        mMapView.invalidate();
    }

    /**
     * 隐藏指南针图层
     */
    public void hideCompass() {
        mMapView.getOverlays().remove(mCompassOverlay);
        mMapView.invalidate();
    }

    /**
     * 打开自由旋转
     */

    public void openRotationGestur() {
        mRotationGestu = new RotationGestureOverlay(mMapView);
        mRotationGestu.setEnabled(true);
        mMapView.getOverlays().add(mRotationGestu);
        mMapView.invalidate();
    }

    /**
     * 关闭自由旋转
     */
    public void closeRotationGestur() {
        mMapView.getOverlays().remove(mRotationGestu);
        mMapView.invalidate();
    }

    /**
     * 显示自己位置
     */
    public void showMyLocation() {
        MyLocationNewOverlay myLocationNewOverlay = new MyLocationNewOverlay(new GpsMyLocationProvider(context), mMapView);
        myLocationNewOverlay.enableMyLocation();
        mMapView.getOverlays().add(myLocationNewOverlay);
        mMapView.invalidate();
    }

    /**
     * 显示网格图层
     */
    public void showGridline() {
        latLonGridlineOverlay2 = new LatLonGridlineOverlay2();
        mMapView.getOverlays().add(latLonGridlineOverlay2);
        mMapView.invalidate();
    }

    /**
     * 关闭网格图层
     */
    public void closeGridline() {
        mMapView.getOverlays().remove(latLonGridlineOverlay2);
        mMapView.invalidate();
    }

    /**
     * 显示地图源
     */
    public void showMapSource() {
        mMapView.getOverlayManager().getTilesOverlay().setEnabled(true);
        mMapView.invalidate();
    }

    /**
     * 显示比例尺
     */
    public void showMetrics() {
        final DisplayMetrics dm = context.getResources().getDisplayMetrics();
        scaleBarOverlay = new ScaleBarOverlay(mMapView);
        scaleBarOverlay.setCentred(true);
        scaleBarOverlay.setAlignBottom(true);
        scaleBarOverlay.setScaleBarOffset(dm.widthPixels / 5, 80);
        mMapView.getOverlays().add(scaleBarOverlay);
        mMapView.invalidate();
    }

    /**
     * 关闭比例尺
     */
    public void closeMetrics() {
        mMapView.getOverlays().remove(scaleBarOverlay);
        mMapView.invalidate();
    }

    /**
     * 显示小地图
     */
    public void showMiniMap() {
        MinimapOverlay overlay = new MinimapOverlay(mainActivity, mMapView.getTileRequestCompleteHandler());
        //overlay.setZoomDifference(12);
        overlay.setPadding(500);
        mMapView.getOverlays().add(overlay);
        mMapView.invalidate();
    }


    /**
     * GO-TO
     * 现在没有用
     */
    public Dialog go_TO() {
        final EditText et = new EditText(context);
        AlertDialog.Builder alterDialog = new AlertDialog.Builder(context)
                //为对话框设置标题
                .setTitle("发送位置")
                .setIcon(android.R.drawable.sym_def_app_icon)
                //为对话设置内容
                .setMessage("输入经度，纬度")
                .setView(et)
                .setPositiveButton("确定", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String st[] = et.getText().toString().split(",");
                        Double a = Double.valueOf(st[0]);
                        Double b = Double.valueOf(st[1]);
                        GeoPoint geoPoint = new GeoPoint(a, b);
                        mMapView.getController().animateTo(geoPoint);
                    }
                })
                .setNegativeButton("取消", new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        //resetRightLayout();
                    }
                });
        AlertDialog dialog = alterDialog.create();
        return dialog;
    }

}
